package com.dhy.domain;

import com.dhy.util.RabbitmqUtil;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * @author 大忽悠
 * @create 2022/5/21 17:35
 */
@Slf4j
public class Server implements Runnable{
    RabbitmqUtil rabbitmqUtil = null;

    @Override
    public void run() {
        try {
            rabbitmqUtil = new RabbitmqUtil("application.yml");
            Channel server = rabbitmqUtil.createChannel();
            //声明客户端和服务器之间通信的队列,这个不是回调队列
            server.queueDeclare(getRpc_queue(), false, false, false, null);
            //清空队列中的消息
            server.queuePurge(getRpc_queue());
            //最多只接收一条消息
            server.basicQos(1);
            //消息rpc_queue队列中客户端发送来的请求
            server.basicConsume(getRpc_queue(),false,
                    //消费队列中的消息
                    (consumerTag, delivery) ->{
                //准备一会要回复的属性
                AMQP.BasicProperties props = new AMQP.BasicProperties().builder()
                                //发送的消息关联的唯一ID
                                .correlationId(delivery.getProperties().getCorrelationId())
                                .build();
                        String reply = new String(delivery.getBody());
                        log.info("客户端回复消息为: {}",reply);
                        if(reply.equals("rpc")){
                            //进行回复
                            server.basicPublish("",delivery.getProperties().getReplyTo(),props,"respect!!!".getBytes(StandardCharsets.UTF_8));
                            //对客户端发送的消息做出回应
                            server.basicAck(delivery.getEnvelope().getDeliveryTag(),false);
                        }
                        },consumerTag -> {});
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }

    private String getRpc_queue() {
        return "rpc_queue";
    }

    public Connection getConn(){
        if(rabbitmqUtil!=null){
          return  rabbitmqUtil.getConnection();
        }
        return null;
    }
}
